<template>
  <div class="environment">
    <el-card class="app-card">
      <template #header>
        <div class="card-header">
          <span>批量创建Chrome环境</span>
        </div>
      </template>
      
      <el-form label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Chrome可执行文件路径">
              <el-input v-model="form.chromePath" readonly placeholder="请选择Chrome可执行文件">
                <template #append>
                  <el-button @click="selectChromePath">选择文件</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="用户数据目录">
              <el-input v-model="form.dataDir" readonly placeholder="请选择数据目录">
                <template #append>
                  <el-button @click="selectDataDir">选择目录</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="环境数量">
              <el-input-number
                v-model="form.count"
                :min="1"
                :max="100"
                size="large"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起始编号">
              <el-input-number
                v-model="form.startNumber"
                :min="1"
                :max="999"
                size="large"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="CDP调试端口">
              <el-input-number
                v-model="form.debugPort"
                :min="9222"
                :max="65535"
                size="large"
              />
              <div class="form-hint">端口将按窗口编号递增: 9222 + 窗口编号</div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-checkbox v-model="form.createShortcuts">创建桌面快捷方式</el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="creating" 
            :disabled="!isFormValid || creating" 
            @click="createEnvironments"
          >
            <el-icon><i-ep-plus /></el-icon>
            批量创建
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 创建进度对话框 -->
    <el-dialog
      v-model="showProgress"
      title="创建进度"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="progress-content">
        <el-progress :percentage="progress" :status="progressStatus" />
        <div class="progress-text">{{ progressText }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 使用别名以避免命名冲突
const iEpPlus = Plus

interface FormData {
  chromePath: string
  dataDir: string
  count: number
  startNumber: number
  debugPort: number
  createShortcuts: boolean
}

const form = reactive<FormData>({
  chromePath: '',
  dataDir: '',
  count: 10,
  startNumber: 1,
  debugPort: 9222,
  createShortcuts: true
})

const creating = ref(false)
const showProgress = ref(false)
const progress = ref(0)
const progressStatus = ref<'success' | 'exception' | 'warning'>('success')
const progressText = ref('')
// 加载状态
const loadingPaths = ref(true)

// 表单验证
const isFormValid = computed(() => {
  return (
    form.chromePath && 
    form.dataDir && 
    form.count > 0 && 
    form.startNumber > 0
  )
})

// 保存当前路径的引用，用于重置时恢复
let savedPaths = {
  chromePath: '',
  dataDir: ''
}

// 获取默认路径
const loadDefaultPaths = async () => {
  try {
    loadingPaths.value = true
    // 从Electron主进程获取默认路径
    const defaultPaths = await window.electronAPI.getDefaultPaths()
    
    // 设置默认路径
    if (defaultPaths.chromePath) {
      form.chromePath = defaultPaths.chromePath
    }
    
    // 使用应用提供的数据目录（目录创建将在主进程处理）
    form.dataDir = defaultPaths.dataDir
    
    // 保存当前路径，用于重置时恢复
    savedPaths = {
      chromePath: form.chromePath,
      dataDir: form.dataDir
    }
  } catch (error) {
    console.error('获取默认路径失败:', error)
    ElMessage.warning('无法自动获取默认路径，请手动选择')
  } finally {
    loadingPaths.value = false
  }
}

// 选择Chrome可执行文件
const selectChromePath = async () => {
  try {
    const path = await window.electronAPI.selectChromeExecutable()
    if (path) {
      form.chromePath = path
    }
  } catch (error) {
    console.error('选择Chrome可执行文件失败:', error)
    ElMessage.error('选择文件失败')
  }
}

// 选择数据目录
const selectDataDir = async () => {
  try {
    const path = await window.electronAPI.selectDirectory()
    if (path) {
      form.dataDir = path
    }
  } catch (error) {
    console.error('选择数据目录失败:', error)
    ElMessage.error('选择目录失败')
  }
}

// 移除了快捷方式目录选择功能

// 组件挂载时加载默认路径
onMounted(() => {
  loadDefaultPaths()
})

// 批量创建环境
const createEnvironments = async () => {
  if (!isFormValid.value) {
    ElMessage.warning('请填写完整表单信息')
    return
  }
  
  try {
    // 显示进度对话框
    showProgress.value = true
    progress.value = 0
    progressText.value = '准备创建环境...'
    
    // 实际创建过程
    for (let i = 0; i < form.count; i++) {
      const currentNum = form.startNumber + i
      const currentPort = form.debugPort + i
      
      // 准备当前环境的配置
      const environmentConfig = {
        chromePath: form.chromePath,
        dataDir: `${form.dataDir}/Profile_${currentNum}`,
        debugPort: currentPort,
        createDesktopShortcut: form.createShortcuts,
        profileNumber: currentNum
      }
      
      // 更新进度信息
      progressText.value = `正在创建环境 ${currentNum}/${form.startNumber + form.count - 1}...`
      
      // 调用主进程创建环境
      await window.electronAPI.createChromeEnvironment(environmentConfig)
      
      // 更新进度
      progress.value = Math.round(((i + 1) / form.count) * 100)
      
      // 短暂延迟，以便用户看到进度
      await new Promise(resolve => setTimeout(resolve, 50))
    }
    
    progressStatus.value = 'success'
    progressText.value = '环境创建完成！'
    
    await new Promise(resolve => setTimeout(resolve, 1000))
    showProgress.value = false
    
    ElMessage.success(`成功创建 ${form.count} 个Chrome环境`)
  } catch (error) {
    console.error('创建环境失败:', error)
    progressStatus.value = 'exception'
    progressText.value = '创建过程中出现错误'
    
    await new Promise(resolve => setTimeout(resolve, 2000))
    showProgress.value = false
    
    ElMessage.error(`创建环境失败: ${error instanceof Error ? error.message : String(error)}`)
  }
}

// 重置表单
const resetForm = () => {
  // 保留自动设置的路径
  form.chromePath = savedPaths.chromePath
  form.dataDir = savedPaths.dataDir
  
  // 只重置其他参数
  form.count = 10
  form.startNumber = 1
  form.debugPort = 9222
  form.createShortcuts = true
}
</script>

<style lang="scss" scoped>
.environment {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .form-hint {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
  }
  
  .progress-content {
    .progress-text {
      margin-top: 10px;
      text-align: center;
      font-size: 14px;
    }
  }
}
</style>